<template>
  <view class="h-100vh flex">
    <CustomNavbar :title="title" left-icon=" " />
    <view class="flex flex-auto items-center justify-center">
      <up-loading-icon mode="circle" text="" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { useConfigStore, useUserStore } from '@/store';

const title = ref('加载中...');
const options = ref<Record<string, string>>({});
const { /* setConfigRank, */configCli, setAddress, setConfigCli } = useConfigStore();
const { token, setUserInfo } = useUserStore();
// 检测没有缓存则请求刷数据，但基本上配置接口只会请求一次
const checkIsNoCache = () => {
  const configCache = uni.getStorageSync<ReturnType<typeof useConfigStore> | ''>('config');
  if (!configCache) {
    return true;
  }
  return Object.keys(configCache).some((key) => {
    // if (key === 'configCli' || key === 'configRank') {
    if (key === 'configCli') {
      return Object.keys(configCache[key]).length === 0;
    }
    else if (key === 'address') {
      return configCache[key].length === 0;
    }
    return false;
  });
};
// 聚合请求配置
const getConfig = async () => {
  // TODO setConfigRank接口有问题不需要缓存看可能
  await Promise.all([/* setConfigRank(), */setAddress(), setConfigCli()]);
  console.log(configCli);
};

const init = () => {
  if (checkIsNoCache()) {
    getConfig();
  }
  if (token) {
    setUserInfo();
  }
};

// 未来可能会通过url、参数等等重定向跳转到指定页面
const pageTo = () => {
  const { token } = useUserStore();
  const url = token ? '/pages/tab/home/index' : '/pages/common/login/index';
  const jumpType = token ? 'switchTab' : 'redirectTo';
  return uni[jumpType]({
    url,
  });
};

init();
onLoad((params: any) => {
  options.value = params;
  pageTo();
});
</script>

<style scoped lang="scss"></style>
